//
//  LSYNovelService.m
//  LSYReader
//
//  Created by sam on 2018/3/22.
//  Copyright © 2018年 okwei. All rights reserved.
//
#import "HTMLKit.h"
#import "NSString+EV.h"
#import "NSDictionary+EV.h"
#import "LSYNovelService.h"
#import "LSYRuleService.h"
#import "LSYHTTPManager.h"

#import "LSYNetUtil.h"
#import "LSYFileUtil.h"

@implementation LSYNovelService

+ (void)getChapterDetail:(LSYBook *)book block:(void (^)(NSString *detailUrl))block {
    if (book.rule.searchToDetail || book.rule.detailChaptersUrl.length>0) {
        LSYHTTPManager *manager = [LSYHTTPManager htmlManager];
        [manager GET:book.bookUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                NSString *detailUrl = [LSYNetUtil chapterDetail:responseObject book:book relativeUrl:[NSURL URLWithString:book.bookUrl]];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (block) {
                        block(detailUrl?:book.bookUrl);
                    }
                });
            });
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (block) {
                block(nil);
            }
        }];
    } else {
        if (block) {
            block(book.bookUrl);
        }
    }
}

+ (void)getChapters:(LSYBook *)book block:(void (^)(NSArray *))block {
    [[self class] getChapterDetail:book block:^(NSString *detailUrl) {
        if (detailUrl) {
            LSYHTTPManager *manager = [LSYHTTPManager htmlManager];
            [manager GET:detailUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    NSArray *chapters = [LSYNetUtil chapters:responseObject book:book relativeUrl:[NSURL URLWithString:detailUrl]];
                    book.chapters = [NSMutableArray arrayWithArray:chapters];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (block) {
                            block(chapters);
                        }
                    });
                });
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSLog(@"%@",error);
                if (block) {
                    block(nil);
                }
            }];
        } else {
            if (block) {
                block(nil);
            }
        }
    }];
}

+ (void)getChapterContent:(LSYChapter *)chapter book:(LSYBook *)book block:(void(^)(NSString *content))block {
    NSString *cache = [LSYNetUtil cacheChapterContent:chapter];
    if (cache.length>0) {
        if (block) {
            block(cache);
        }
        return;
    }
    
    LSYHTTPManager *manager = [LSYHTTPManager htmlManager];
    [manager GET:chapter.chapterUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSString *content = [LSYNetUtil chapterContent:responseObject rule:book.rule];
            // save chate
            [LSYNetUtil saveCahpterContent:content chapter:chapter];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (block) {
                    block(content);
                }
            });
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (block) {
            block(nil);
        }
    }];
}

+ (void)searchNovel:(LSYParseModel *)rule key:(NSString *)key novels:(void (^)(NSArray *,NSString *))block {
    NSString *searchUrl = [[NSString stringWithFormat:rule.searchUrl,key] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    rule.targetUrl = [NSURL URLWithString:searchUrl];
    LSYHTTPManager *manager = [LSYHTTPManager htmlManager];
    [manager GET:searchUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray *books = [LSYNetUtil books:responseObject rule:rule relativeUrl:[NSURL URLWithString:searchUrl]];
        if (block) {
            block(books,nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if(block) {
            block(nil,nil);
        }
    }];
}

+ (void)searchBookAndChapter:(LSYReadModel *)model rule:(LSYParseModel *)rule block:(void(^)(BOOL success))block {
    LSYBook *book = model.netBook;
    [[self class] searchNovel:rule key:book.bookName novels:^(NSArray *novels, NSString *moreUrl) {
        if (novels.count>0) {
            LSYBook *tmpBook = nil;
            for (LSYBook *enumBook in novels) {
                if ([enumBook isTheSameBook:book]) {
                    tmpBook = enumBook;
                    break;
                }
            }
            // found
            if (tmpBook) {
                //search chapters
                [[self class] getChapters:tmpBook block:^(NSArray *chapters) {
                    if (chapters.count>0) {
                        //查找章节
                        LSYChapterModel *chapter = [model.chapters objectAtIndex:model.record.chapter];
                        NSInteger index = 0;
                        BOOL found = NO;
                        for (LSYChapter *eChapter in chapters) {
                            if ([chapter.title isEqualToString:eChapter.chapterName]) {
                                found = YES;
                                break;
                            }
                            index ++;
                        }
                        if (found) {
                            LSYReadModel *tmpModel = [[LSYReadModel alloc] initWithNetBook:tmpBook];
                            tmpModel.record.chapter = index;
                            tmpModel.record.chapterCount = chapters.count;
                            tmpModel.record.chapterModel = [tmpModel.chapters objectAtIndex:index];
                            [model updateReadModel:tmpModel];
                            if (block) {
                                block(YES);
                            }
                        } else {
                            if (block) {
                                block(NO);
                            }
                        }
                    } else {
                        if (block) {
                            block(NO);
                        }
                    }
                }];
            } else {
                if (block) {
                    block(NO);
                }
            }
        } else {
            if (block) {
                block(NO);
            }
        }
    }];
}


+ (void)batchSearchNovel:(LSYParseModel *)rule book:(LSYBook *)book novels:(void (^)(BOOL found))block {
    NSString *searchUrl = [[NSString stringWithFormat:rule.searchUrl,book.bookName] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    LSYHTTPManager *manager = [LSYHTTPManager htmlManager];
    manager.requestSerializer.timeoutInterval = 20;
    [manager GET:searchUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            BOOL found = NO;
            if ([responseObject isKindOfClass:[NSData class]] && [(NSData *)responseObject length]>0) {
                NSArray *books = [LSYNetUtil books:responseObject rule:rule relativeUrl:[NSURL URLWithString:searchUrl]];
                for (LSYBook *tmpBook in books) {
                    if ([tmpBook isTheSameBook:book]) {
                        found = YES;
                        break;
                    }
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                if (block) {
                    block(found);
                }
            });
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (block) {
            block(NO);
        }
    }];
}

+ (void)batchSearch:(LSYBook *)book block:(void(^)(NSMutableArray *rules))block {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSArray *rules = [[LSYRuleService service] rules];
        NSMutableArray *results = [NSMutableArray array];
        dispatch_group_t group = dispatch_group_create();
        for (LSYParseModel *rule in rules) {
            dispatch_group_enter(group);
            [[self class] batchSearchNovel:rule book:book novels:^(BOOL found) {
                if(found) {
                    [results addObject:rule];
                }
                dispatch_group_leave(group);
            }];
        }
        dispatch_group_notify(group, dispatch_get_main_queue(), ^{
            if (block) {
                block(results);
            }
        });
    });
}


@end
